﻿using System;
using System.Data.SqlClient;

namespace MoneyRetrievals
{
    public class Program
    {
        public static void GetMoneyRetrievals(
            SqlConnection dbCon, string cardNumber, string cardPin)
        {
            SqlTransaction moneyRetrievalsTransaction = 
                dbCon.BeginTransaction();

            SqlCommand selectAccount = new SqlCommand();
            selectAccount.Connection = dbCon;
            selectAccount.Transaction = moneyRetrievalsTransaction;
            selectAccount.CommandText =
                "SELECT * " + 
                "FROM CardAccounts " + 
                "WHERE CardNumber = @cardNumber";
            selectAccount.Parameters.Add("@cardNumber", cardNumber);

            SqlDataReader reader = selectAccount.ExecuteReader();
            using (reader)
            {
                if (reader.Read() == false)
                {
                    moneyRetrievalsTransaction.Rollback();
                    throw new ArgumentException("Invalid card number.");
                }
                if ((string)reader["CardPIN"] != cardPin)
                {
                    moneyRetrievalsTransaction.Rollback();
                    throw new ArgumentException("Invalid PIN number.");
                }
            }

            SqlCommand getMoneyRetrievals = new SqlCommand();
            getMoneyRetrievals.Connection = dbCon;
            getMoneyRetrievals.Transaction = moneyRetrievalsTransaction;
            getMoneyRetrievals.CommandText =
                "SELECT * " + 
                "FROM AccountTransactions " + 
                "WHERE CardNumber = @cardNumber";
            getMoneyRetrievals.Parameters.Add("@cardNumber", cardNumber);
            SqlDataReader moneyRetrievals = getMoneyRetrievals.ExecuteReader();
            PrintMoneyRetrievals(moneyRetrievals);
            moneyRetrievalsTransaction.Commit();
        }

        public static void PrintMoneyRetrievals(SqlDataReader reader)
        {
            using (reader)
            {
                if (!reader.Read())
                {
                    Console.WriteLine("There are no transactions made from that card.");
                }
                else
                {
                    do
                    {
                        Console.WriteLine("{0} -> {1} -> {2} -> {3}", reader["Id"],
                            reader["CardNumber"], reader["TransactionDate"], reader["Amount"]);
                    } while (reader.Read());
                }
            }
        }

        public static void Main()
        {
            SqlConnection dbCon = new SqlConnection(
                "Server=.\\SQLEXPRESS; Database=atm; Integrated Security=true");
            dbCon.Open();
            using (dbCon)
            {
                GetMoneyRetrievals(dbCon, "1785471147", "3445");
            }
        }
    }
}
